package com.yaokai.springbootreabbitmq.controller;

import com.yaokai.springbootreabbitmq.callback.MyCallBack;
import com.yaokai.springbootreabbitmq.config.ConfirmConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

@RestController
@RequestMapping("/confirm")
@Slf4j
public class ProducerController {

    public static final String CONFIRM_EXCHANGE_NAME = ConfirmConfig.CONFIRM_EXCHANGE_NAME;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MyCallBack myCallBack;

    //依赖注入rabbitTemplate之后设置它的回调对象
    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(myCallBack);
    }

    /**
     * 消息回调和退回
     * @param message
     */
    @GetMapping("sendMessage/{message}")
    public void sendMessage(@PathVariable String message){

        //指定消息id为1
        CorrelationData correlationData1 = new CorrelationData("1");
        String routinKey = "key1";
        rabbitTemplate.convertAndSend(CONFIRM_EXCHANGE_NAME,routinKey,message+routinKey,correlationData1);
        log.info(routinKey+"发送消息内容：{}",message+routinKey);

        CorrelationData correlationData2 = new CorrelationData("2");
        routinKey = "key2";
        rabbitTemplate.convertAndSend(CONFIRM_EXCHANGE_NAME,routinKey,message+routinKey,correlationData2);
        log.info(routinKey+"发送消息内容：{}",message+routinKey);
    }



}
